import 'dart:async';

import 'package:common_utils/common_utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/helper.dart';
import 'package:yp/router.dart';
import 'package:yp/services/api.dart';
import 'package:yp/utils/util.dart';

import 'state.dart';

class MallVerificationCodeLoginLogic extends GetxController {
  final state = MallVerificationCodeLoginState();
  var arguments = Get.arguments;

  @override
  void onInit() {
    super.onInit();

    state.phoneTextController = TextEditingController();
    state.phoneFocusNode = FocusNode();

    state.passwordTextController = TextEditingController();
    state.passwordFocusNode = FocusNode();

    state.choosePrivacyAgreement = true; //false;
    state.loginBool = true; //false;
  }

  // 隐私协议 选择事件
  void choosePrivacyAgreement(bool chooseBool) {
    state.choosePrivacyAgreement = chooseBool;
    if (state.phoneTextController.text != '' &&
        state.passwordTextController.text != '' &&
        state.choosePrivacyAgreement) {
      state.loginBool = true;
    } else {
      state.loginBool = false;
    }
    update();
  }

  // 输入框内容改变 事件
  void textControllerClick() {
    print('11111  textControllerClick');
    if (state.phoneTextController.text != '' &&
        state.passwordTextController.text != '' &&
        state.choosePrivacyAgreement) {
      state.loginBool = true;
    } else {
      state.loginBool = false;
    }
    update();
  }

  //请求发送验证码
  void sendSms() {
    var params = {
      "mobile": state.phoneTextController.text,
      "verify_code_type": "login"
    };
    Api.sendSms(params).listen((event) {
      state.smsData = event;
      toast("验证码已发送,请注意查收");
      update();
    });

    state.timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (state.seconds == 0) {
        state.timer?.cancel();
        state.verifyStr = '重新发送';
        state.seconds = 60;
        update();
        return;
      }
      state.seconds = --state.seconds;
      state.verifyStr = "已发送${state.seconds}s";
      // print("已发送${state.seconds}s");
      update();
    });
  }

  /// 登录
  void onSubmit() {
    if (state.phoneTextController.text.isEmpty) {
      toast("请输入手机号");

      return;
    }
    if (!RegexUtil.isMobileSimple(state.phoneTextController.text)) {
      toast("手机号格式错误");

      return;
    }
    if (state.passwordTextController.text.isEmpty) {
      toast("请输入验证码");

      return;
    }

    var params = {
      "channel_num_id": 99,
      "mobile": state.phoneTextController.text,
      "sms_verify_code": state.passwordTextController.text,
      "sms_verify_token": state.smsData["token"],
      "sms_verify_type": "login",
      'use_platform': 2
    };
    Api.registMember(params).listen((event) {
      print("event");
      if (event["code"] != 0) {
        if (event["code"] == -147101) {
          toast("短信验证码错误");
        } else {
          if (event["code"] == 401) {
            toast(event["message"]);
          } else {
            toast('登录错误：${event["message"]}');
          }
        }
      } else {
        state.timer?.cancel();

        SpUtil.putString('empeName', event["usr_name"] ?? '');
        SpUtil.putInt('empeNumId', event["usr_num_id"]);
        SpUtil.putString('token', event["access_token"]);
        SpUtil.putInt('is_new_user', event["is_new_user"]);
        SpUtil.putString('number', state.phoneTextController.text);
        if (event["sign"] != null && event["sign"] != '') {
          SpUtil.putString('usr_phone_num', event["usr_phone_num"]);
          SpUtil.putString('sign', event["sign"]);
          SpUtil.putInt('time_stamp', event["time_stamp"]);
        }
        if (kIsWeb) {
          var page = getQueryVariable('page').toString();

          if (page == "random_amount") {
            arguments = {
              "activity_num_id": getQueryVariable('activity_num_id'),
              "event_num_id": getQueryVariable('event_num_id'),
            };
          }
          if (page == "collect_coupons") {
            arguments = {
              "from_usr_num_id": getQueryVariable('from_usr_num_id'),
              "seriesID": getQueryVariable('seriesID'),
            };
          }
        }
        toast("登录成功");
        if (arguments != null) {
          argumentsRouter(arguments);
        } else {
          Get.offAllNamed(RouteConfig.main);
        }
      }
    });
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
    state.timer?.cancel();
  }
}
